
from time import sleep
from requests import request
import json
from urllib.parse import urlparse, parse_qs

from config import (
    REFERRALS_ACCOUNTS_FOLDER_PATH,
    MASTER_ACCOUNTS_FILE_PATH,
    _2CAPTCHA_API_KEY,
    GOOGLE_KEY,
    PAGEURL,
)
from log import logger
from utils import parse_1secmail_mail


def get_recaptcha_response():

    url = 'https://2captcha.com/in.php'
    json_data = {
        'key': _2CAPTCHA_API_KEY,
        'method': 'userrecaptcha',
        'googlekey': GOOGLE_KEY,
        'pageurl': PAGEURL,
    }

    response = request('POST', url, json=json_data)

    if not response.ok:
        logger.error(f'code: ZbWMApECQ6N5htGK; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not 'OK' in response.text:
        logger.error(f'code: ePbkkEhYbQ74t2HD; {response.status_code} {response.text}')
        return {'status': 'error'}

    captcha_request_id = response.text[3:]
    for _ in range(40):
        url = 'https://2captcha.com/res.php'
        params = {
            'key': _2CAPTCHA_API_KEY,
            'action': 'get',
            'id': captcha_request_id,
        }
        response = request('GET', url, params=params)
        if 'CAPCHA_NOT_READY' in response.text:
            sleep(10)
        elif 'ERROR' in response.text > -1:
            logger.error(f'code: qrqGGazA99mJv43h; {response.text}')
            return {'status': 'error'}
        elif 'OK' in response.text:
            result = str(response.text[3:])
            break
        else:
            logger.error(f'code: B86hpwMBVDng9mPE; {response.text}')
            return {'status': 'error'}

    return {
        'status': 'success',
        'data': {
            'recaptcha_response': result
        }
    }


def set_user(email, wallet_address, referral_code, recaptcha_response, proxies, user_agent):

    headers = {
        'Host': 'mntixvzfga.execute-api.us-east-1.amazonaws.com',
        'User-Agent': user_agent,
        'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://mntixvzfga.execute-api.us-east-1.amazonaws.com/',
        'Content-Type': 'text/plain;charset=UTF-8',
        'Origin': 'https://helixmetaverse.com',
        # 'Content-Length': '627',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'cross-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
        'Connection': 'close',
    }

    data = {
        'email': email,
        'wallet': wallet_address,
        'r_id': referral_code,
        'g-recaptcha-response': recaptcha_response,
    }
    str_data = json.dumps(data, separators=(',', ':'))

    response = request(
        'POST', 'https://mntixvzfga.execute-api.us-east-1.amazonaws.com/setUser',
        headers=headers, data=str_data, proxies=proxies, verify=False
    )
    if not response.ok:
        logger.error(f'code: fR94M9FjtpN7L4U5; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not 'uuid' in response.text:
        logger.error(f'code: YHdKf5hKYZz7AY8j; {response.text}')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': {
            'status_code': response.status_code,
            'uuid': response.json()['uuid']
        }
    }


def verification_email(email, _from, subject, proxies, user_agent):

    parse_1secmail_mail_result = parse_1secmail_mail(email, _from, subject, proxies)
    if parse_1secmail_mail_result['status'] != 'success':
        logger.error('code: yxWXwWvtDSq55TCw')
        return {'status': 'error'}

    mail_text_body = parse_1secmail_mail_result['data']['json']['textBody']
    verification_url = mail_text_body[75:-2]
    logger.debug(f'verification url: {verification_url}')

    response = request(
        'GET', verification_url, 
        proxies=proxies
    )
    if not response.ok:
        logger.error(f'code: nLRcFRrrWa44kR9p; {response.status_code} {response.text}')
        return {'status': 'error'}

    uuid = str(parse_qs(urlparse(response.url).query)['uuid'][0])
    secret = str(parse_qs(urlparse(response.url).query)['secret'][0])

    logger.debug([uuid, secret])


    headers = {
        'Host': 'mntixvzfga.execute-api.us-east-1.amazonaws.com',
        'User-Agent': user_agent,
        'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.5',
        # 'Accept-Encoding': 'gzip, deflate',
        'Referer': 'https://mntixvzfga.execute-api.us-east-1.amazonaws.com/',
        'Content-Type': 'text/plain;charset=UTF-8',
        'Origin': 'https://helixmetaverse.com',
        # 'Content-Length': '36',
        'Dnt': '1',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'cross-site',
        'Sec-Gpc': '1',
        # Requests doesn't support trailers
        # 'Te': 'trailers',
    }

    data = {
        'uuid': uuid,
        'secret': secret,
    }
    str_data = json.dumps(data, separators=(',', ':'))

    response = request(
        'PUT', 'https://mntixvzfga.execute-api.us-east-1.amazonaws.com/setUser',
        headers=headers, data=str_data, proxies=proxies, verify=False
    )
    if not response.ok:
        logger.error(f'code: Fg2yDztAfemj7sjw; {response.status_code} {response.text}')
        return {'status': 'error'}
    if not 'uuid' in response.text:
        logger.error(f'code: 2erjzpqSjRJSH4nt; {response.text}')
        return {'status': 'error'}
    logger.debug([response.status_code, response.text])

    return {'status': 'success'}


def write_account_data(referral_code, account_data):

    if referral_code:
        with open(REFERRALS_ACCOUNTS_FOLDER_PATH+'/'+referral_code, 'a') as f:
            f.write(str(account_data)+'\n')
    else:
        with open(MASTER_ACCOUNTS_FILE_PATH, 'a') as f:
            f.write(str(account_data)+'\n')
